#include "helpwidget.h"

HelpWidget::HelpWidget(QString url, MAWindow *mgr) {
  setObjectName("helpwidget");
  m_browser = new QTabWidget(this);
  setWidget(m_browser);


  m_flist = new QListWidget;
  // Populate the list widget
  QFile *file = new QFile(url + "/modules.txt");
  if (!file->open(QFile::ReadOnly | QIODevice::Text))
  {
  }
  else
  {
    QTextStream t(file);
    while (!t.atEnd()) {
      QString line(t.readLine());

      new QListWidgetItem(line,m_flist);
    }
  }
  delete file;
  connect(m_flist,SIGNAL(itemDoubleClicked(QListWidgetItem*)),
          mgr,SLOT(activateHelpModule(QListWidgetItem*)));
  connect(m_flist,SIGNAL(itemActivated(QListWidgetItem*)),
          mgr,SLOT(activateHelpModule(QListWidgetItem*)));

  QTreeWidget *m_tindex = new QTreeWidget;

  connect(m_tindex,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
          mgr,SLOT(activateHelpModule(QTreeWidgetItem*,int)));
  connect(m_tindex,SIGNAL(itemActivated(QTreeWidgetItem*,int)),
          mgr,SLOT(activateHelpModule(QTreeWidgetItem*,int)));

  m_tindex->setColumnCount(1);
  m_tindex->setHeaderLabels(QStringList() << "");
  file = new QFile(url + "/sectable.txt");
  QRegExp reg("\\+\\s*\\((\\b\\w+\\b)\\)\\s*(\\b.*)");
  if (!file->open(QFile::ReadOnly | QIODevice::Text))
    QMessageBox::warning(this,"Cannot Find Section Index",tr("Không tìm thấy tập tin sectable.txt trong ")+url,QMessageBox::Ok,QMessageBox::NoButton,QMessageBox::NoButton);
  else {
    QTextStream t(file);
    t.setCodec("UTF-8");
    QTreeWidgetItem *prev = NULL;
    while (!t.atEnd()) {
      QString line(t.readLine());
      if (reg.indexIn(line) < 0)
        prev = new QTreeWidgetItem(m_tindex,QStringList() << line);
      else {
        new QTreeWidgetItem(prev,QStringList() << reg.cap(2) << reg.cap(1));
      }
    }
  }
  delete file;
  m_browser->addTab(m_tindex,tr("Chỉ mục"));
  m_browser->addTab(m_flist,tr("Các chủ đề"));
  m_browser->addTab(new HelpSearcher(m_browser,url,mgr),tr("Tìm kiếm"));
}
